package it.gat.client.view;

import it.gat.controller.UtenteController;
import it.gat.controller.utils.GatSession;
import it.gat.model.Utente;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JPasswordField;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class PasswordDialog extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JPasswordField txtOldPassword;
	private JPasswordField txtNewPassword;

	/**
	 * Create the dialog.
	 */
	public PasswordDialog() {
		setBounds(100, 100, 267, 159);
		getContentPane().setLayout(null);
		contentPanel.setBounds(0, 0, 268, 76);
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel);
		contentPanel.setLayout(null);
		{
			JLabel lblNuovaPassword = new JLabel("Nuova password");
			lblNuovaPassword.setBounds(10, 36, 90, 14);
			contentPanel.add(lblNuovaPassword);
		}
		{
			JLabel label = new JLabel("Vecchia password");
			label.setBounds(10, 11, 90, 14);
			contentPanel.add(label);
		}
		
		txtOldPassword = new JPasswordField();
		txtOldPassword.setBounds(110, 8, 128, 20);
		contentPanel.add(txtOldPassword);
		
		txtNewPassword = new JPasswordField();
		txtNewPassword.setBounds(110, 33, 128, 20);
		contentPanel.add(txtNewPassword);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setBounds(10, 74, 229, 33);
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if (String.valueOf(txtOldPassword.getPassword()).equals(GatSession.getInstance().getUtenteLoggato().getPassword()))
								{
							UtenteController uc = new UtenteController();
							Utente utente = GatSession.getInstance().getUtenteLoggato();
							utente.setPassword(String.valueOf(txtNewPassword.getPassword()));
							uc.updateUtente(utente);
							
								}
						else
						{
							JOptionPane.showMessageDialog(null,"Vecchia password non corretta","Errore",JOptionPane.ERROR_MESSAGE);
						}
						dispose();
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}
}
